package com.sophic_tech.hkb.service.resource.Impl;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.sophic_tech.hkb.entity.ResourceModel;
import com.sophic_tech.hkb.entity.ResourceModelVO;
import com.sophic_tech.hkb.entity.Result;
import com.sophic_tech.hkb.entity.UserModel;
import com.sophic_tech.hkb.mapper.ResourceMapper;
import com.sophic_tech.hkb.service.resource.GetResourceList;
import com.sophic_tech.hkb.service.resource.postResource;
import com.sophic_tech.hkb.utils.JWTUtils;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.security.SignatureException;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class ResourceService implements GetResourceList, postResource {


    @Resource
    private ResourceMapper resourceMapper;

    @Override
    public Result getRecommendResourceList(String token, int pageSize) {
        log.info("开始获取资源列表，请求Token: {}, 每页数量: {}", token, pageSize);

        if (token == null) {
            log.warn("获取资源列表失败：Token为空");
            return Result.error(401, "未登录");
        }

        try {
            DecodedJWT decodedjwt = JWTUtils.verify(token);
            int currentUserId = decodedjwt.getClaim("id").asInt();
            log.debug("当前用户ID: {}", currentUserId);

            Page<ResourceModelVO> page = new Page<>(1, pageSize);

            MPJLambdaWrapper<ResourceModel> wrapper = new MPJLambdaWrapper<ResourceModel>()
                    .selectAll(ResourceModel.class)
                    .select(UserModel::getUsername)
                    .leftJoin(UserModel.class, UserModel::getId, ResourceModel::getUserId)
                    .orderByDesc(ResourceModel::getCreateTime);
            log.debug("JOIN查询条件构建完成: {}", wrapper.getCustomSqlSegment());

            Page<ResourceModelVO> resourcePage = resourceMapper.selectJoinPage(
                    page,
                    ResourceModelVO.class,
                    wrapper
            );

            List<ResourceModelVO> resourceModelVOList = resourcePage.getRecords();

            log.info("资源列表查询成功，共 {} 条资源，总页数: {}, 总记录数: {}", resourceModelVOList.size(), resourcePage.getPages(), resourcePage.getTotal());

            if (resourceModelVOList.isEmpty()) {
                log.warn("数据库中未找到资源");
                return Result.error(404, "获取资源列失败，数据库中未找到资源");
            }

            Map<String, Object> resultData = new HashMap<>();
            resultData.put("records", resourceModelVOList);
            resultData.put("total", resourcePage.getTotal());
            resultData.put("pages", resourcePage.getPages());
            resultData.put("current", resourcePage.getCurrent());
            resultData.put("size", resourcePage.getSize());

            return Result.success("获取资源列表成功", resultData);

        } catch (ExpiredJwtException e) {
            log.error("Token已过期，错误信息: {}", e.getMessage());
            return Result.error(401, "token已过期，请重新登录");
        } catch (SignatureException e) {
            log.error("Token签名验证失败，错误信息: {}", e.getMessage());
            return Result.error(401, "token签名错误，请重新登录");
        } catch (Exception e) {
            log.error("获取资源列表时发生未知异常", e);
            return Result.error(500, "获取资源列表失败");
        }
    }
    @Override
    public Result postResource(String token, ResourceModel model) {
        log.info("开始发布资源，请求参数预处理");

        if (token == null || token.trim().isEmpty()) {
            log.warn("发布资源失败：Token为空或空白");
            return Result.error(401, "未登录");
        }
        
        try {
            log.debug("开始验证Token: {}", token);
            DecodedJWT decodedjwt = JWTUtils.verify(token);
            int currentUserId = decodedjwt.getClaim("id").asInt();
            log.info("用户Token验证成功，用户ID: {}", currentUserId);

            if (model == null) {
                log.warn("发布资源失败：资源模型为空");
                return Result.error(400, "资源数据不能为空");
            }

            if (!validateResourceModel(model)) {
                log.warn("发布资源失败：资源数据验证不通过");
                return Result.error(400, "资源数据不完整或格式错误");
            }
            model.setUserId(currentUserId);

            if (model.getStatus() == null || model.getStatus().trim().isEmpty()) {
                model.setStatus("normal");
                log.debug("设置资源默认状态为: normal");
            }

            if (model.getCreateTime() == null) {
                model.setCreateTime(java.time.LocalDateTime.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                log.debug("设置资源创建时间为: {}", model.getCreateTime());
            }

            log.info("开始执行资源插入操作，用户ID: {}, 资源标题: {}", currentUserId, model.getTitle());
            int insertResult = resourceMapper.insert(model);

            if (insertResult > 0) {
                log.info("资源发布成功，资源ID: {}, 用户ID: {}", model.getId(), currentUserId);
                Map<String, Object> resultData = new HashMap<>();
                resultData.put("resourceId", model.getId());
                return Result.success("资源发布成功", resultData);
            } else {
                log.error("资源发布失败：数据库插入操作未影响任何记录，用户ID: {}", currentUserId);
                return Result.error(500, "资源发布失败，请稍后重试");
            }
            
        } catch (ExpiredJwtException e) {
            log.error("Token已过期，错误信息: {}", e.getMessage());
            return Result.error(401, "token已过期，请重新登录");
        } catch (SignatureException e) {
            log.error("Token签名验证失败，错误信息: {}", e.getMessage());
            return Result.error(401, "token签名错误，请重新登录");
        } catch (Exception e) {
            log.error("发布资源时发生未知异常", e);
            return Result.error(500, "发布资源失败");
        }
    }

    private boolean validateResourceModel(ResourceModel model) {

        if (model.getTitle() == null || model.getTitle().trim().isEmpty()) {
            log.warn("资源标题不能为空");
            return false;
        }

        if (model.getTitle().length() > 255) {
            log.warn("资源标题长度超过限制");
            return false;
        }

        if (model.getIntroduction() == null || model.getIntroduction().trim().isEmpty()) {
            log.warn("资源介绍不能为空");
            return false;
        }

        if (model.getResourceTag() != null && !model.getResourceTag().matches("^[\u4e00-\u9fa5a-zA-Z0-9,]+$")) {
            log.warn("资源标签格式不正确，只允许中文、英文、数字和逗号");
            return false;
        }

        if (model.getIsVipOnly() != null && model.getIsVipOnly() != 0 && model.getIsVipOnly() != 1) {
            log.warn("VIP权限设置不正确，必须为0或1");
            return false;
        }
        
        log.debug("资源数据验证通过: {}", model.getTitle());
        return true;
    }
}